/*
 * Copyright (c) 2004-2006 SchemeWay Project. All rights reserved.
 */
package org.schemeway.plugins.schemescript.editor;

import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.*;
import org.eclipse.help.*;
import org.eclipse.jface.text.ITextSelection;

/**
 * @author SchemeWay Project.
 *
 */
public class SelectionContext implements IContext2 {
	private IHelpResource[] helpResources;
	private String text;
	private String title;

	/**
	 * 
	 */
	public SelectionContext(IContext context, ITextSelection selection) {
		Assert.isNotNull(selection);
		
		//Set the title and text
		if (context instanceof IContext2) {
			title = ((IContext2) context).getTitle();
		} else {
			title = "";
		}
		
		if (context != null) {
			text = context.getText();
		}
		
		if (text == null) {
			text = "";
		}
		//The text that is selected in the view
		String selectedText = selection.getText();
		
		//If something is selected
		if (!selectedText.equals("")) {
			//This ArrayList will hold the resources which match the selected text
			List<IHelpResource> resources = new ArrayList<IHelpResource>();
			
			//Look through all the topics and get the ones that match the selected text
			if (context != null) {
				IHelpResource[] contextTopics = context.getRelatedTopics();
				if (contextTopics != null) {
					for (int i = 0; i < contextTopics.length; i++) {
						if (selectedText.contains(contextTopics[i].getLabel()) 
								|| contextTopics[i].getLabel().contains(selectedText)) {
							resources.add(contextTopics[i]);
						}
					}
				}
			}
			helpResources = resources.toArray(new IHelpResource[resources.size()]);
		}
	}

	@Override
	public String getCategory(IHelpResource topic) {
		return null;
	}

	@Override
	public String getStyledText() {
		return text;
	}

	@Override
	public String getTitle() {
		return title;
	}

	@Override
	public IHelpResource[] getRelatedTopics() {
		return helpResources;
	}

	@Override
	public String getText() {
		return text;
	}

}
